/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.cfweb.lognode.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Keeps sending random data to the specified address.
 */
@Component
public final class LognodeClient {
	@Value("#{configProperties['lognode.ip']}")
    private String  host;
    @Value("#{configProperties['lognode.port']}")
    private int port;
    
    public void notify(String msg) throws InterruptedException{
    	 EventLoopGroup group = new NioEventLoopGroup();
         try {
             Bootstrap b = new Bootstrap();
             b.group(group)
              .channel(NioSocketChannel.class)
              .handler(new ChannelInitializer<SocketChannel>() {
                  @Override
                  protected void initChannel(SocketChannel ch) throws Exception {
                     /*ChannelPipeline p = ch.pipeline();
                      p.addLast(new WriterHandler());*/
                  }
              });

             // Make the connection attempt.
             ChannelFuture f = b.connect(host, port).sync();
             final ByteBuf byteBuf = f.channel().alloc().buffer(msg.getBytes().length);
             byteBuf.writeBytes(msg.getBytes());
             f.channel().writeAndFlush(byteBuf);
             f.channel().close();
             // Wait until the connection is closed
             f.channel().closeFuture().sync();
         } finally {
             group.shutdownGracefully();
         }
    }
    
    public static void main(String[] args) throws InterruptedException{
    	/*LognodeClient client=new LognodeClient();
    	client.notify("60 get patterns [GP] appid:e48f63f1-3660-46b3-9d97-8dbfe1046943");*/
    	String msg="<14> fet";
    	 final ByteBuf byteBuf =Unpooled.buffer(msg.length());
         byteBuf.writeBytes(msg.getBytes());
         System.out.println(byteBuf.getUnsignedByte(0)-'0');
    }
}
